using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Speech.Recognition;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
using System.IO;
using VoiceCommander.Configuration;

namespace VoiceCommander
{
	public partial class frmMain : Form
	{
		public frmMain()
		{
			InitializeComponent();

			#region Load the Recognition Engines

			ReadOnlyCollection<RecognizerInfo> engines = SpeechRecognitionEngine.InstalledRecognizers();

			if (engines.Count == 0)
			{
				throw new Exception("There are no valid engines installed");
			}

			cmbEngine.DisplayMember = "Description";
			foreach (RecognizerInfo engine in engines)
			{
				cmbEngine.Items.Add(engine);
			}

			cmbEngine.SelectedIndex = 0;
			
			#endregion

		}

		private void cmdBrowse_Click(object sender, EventArgs e)
		{
			DialogResult res = dlgConfiguration.ShowDialog();

			if (res == DialogResult.OK)
			{
				txtConfigFile.Text = dlgConfiguration.FileName;
			}
		}

		private void cmdStart_Click(object sender, EventArgs e)
		{
			try
			{
				if (cmbEngine.SelectedIndex == -1)
				{
					throw new Exception("Select a Recognition Engine.");
				}

				if (txtConfigFile.Text.Length == 0)
				{
					throw new Exception("Specify a configuration file.");
				}

				CommandListType configuration = null;
				using (Stream configFile = File.OpenRead(txtConfigFile.Text))
				{
					XmlSerializer deserializer = new XmlSerializer(typeof(CommandListType));

					configuration = (CommandListType)deserializer.Deserialize(configFile);
				}

				frmKeySender keySender = new frmKeySender(configuration, (RecognizerInfo)cmbEngine.SelectedItem);
				keySender.ShowDialog();
			}
			//catch (Exception ex)
			//{
			//    MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			//}
			catch (OutOfMemoryException ex)
			{
			}
		}
	}
}